package com.lingxu.base.common.util;

//import com.spire.pdf.PdfDocument;
//import com.spire.pdf.PdfPageBase;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.ooxml.extractor.POIXMLTextExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;

import java.io.*;

/**
 * @Description: 文件内容读取工具类
 * @Author: 朱家池
 * @Date:   2021-08-05
 * @Version: V1.0.1
 */
public class ReadFileUtil {

    /**
     * JSON字符串特殊字符处理
     *
     * @param s
     * @return String
     */
    public static String stringJson(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '\"':
                    sb.append("\\\"");
                    break;
                case '\\':
                    sb.append("\\\\");
                    break;
                case '/':
                    sb.append("\\/");
                    break;
                case '\b':
                    sb.append("\\b");
                    break;
                case '\f':
                    sb.append("\\f");
                    break;
                case '\n':
                    sb.append("\\n");
                    break;
                case '\r':
                    sb.append("\\r");
                    break;
                case '\t':
                    sb.append("\\t");
                    break;
                default:
                    sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * word读取工具
     *
     * @param path
     * @return
     */
//    public static String readWord(String path,String suffix) {
//        String buffer = "";
//        try {
//            if (suffix.equals("doc")) {
//                InputStream is = new FileInputStream(new File(path));
//                WordExtractor ex = new WordExtractor(is);
//                buffer = ex.getText();
//                ex.close();
//            } else if (suffix.equals("docx")) {
//                OPCPackage opcPackage = POIXMLDocument.openPackage(path);
//                POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
//                buffer = extractor.getText();
//                extractor.close();
//            } else {
//                System.out.println("此文件不是word文件！");
//            }
//        } catch (Exception e) {
//            //e.printStackTrace();
//        }
//        return stringJson(buffer);
//    }


    public static String readWord(String path,String suffix) {
        String buffer = "";
        try {
            if(suffix.equals("doc")) {
                try {
                    WordExtractor wordExtractor = new WordExtractor(new FileInputStream(new File(path)));
                    buffer = wordExtractor.getText();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if(suffix.equals("docx")) {
                OPCPackage opcPackage = POIXMLDocument.openPackage(path);
                POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
                buffer = extractor.getText();
                extractor.close();
            } else {
                System.out.println("此文件不是word文件！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer;
    }


    /**
     * excel读取工具
     *
     * @param path
     * @return
     */
    public static String readExcel(String path,String suffix) {
        String buffer = "";
        try {
            InputStream is = new FileInputStream(path);
            if (suffix.equals("xls")) {
                HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
                ExcelExtractor extractor = new ExcelExtractor(wb);
                extractor.setIncludeSheetNames(true);
                extractor.setFormulasNotResults(true);
                extractor.setIncludeCellComments(true);
                buffer = extractor.getText();
            } else if (suffix.equals("xlsx")) {
                OPCPackage opcPackage = POIXMLDocument.openPackage(path);
                POIXMLTextExtractor extractor = new XSSFExcelExtractor(opcPackage);
                buffer = extractor.getText();
                extractor.close();
            } else {
                System.out.println("此文件不是excel文件！");
                return "";
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return stringJson(buffer);
    }

    /**
     * pdf读取工具
     *
     * @param path
     * @return
     */
//    public static String readPdf(String path) {
//        String buffer = "";
//        try {
//            //创建PdfDocument实例
//            PdfDocument pdf = new PdfDocument();
//            //加载PDF文件
//            pdf.loadFromFile(path);
//            PdfPageBase page = null;
//            //遍历PDF页面，获取文本
//            for (int i = 1; i < pdf.getPages().getCount(); i++) {
//                page = pdf.getPages().get(i);
//                buffer += page.extractText(true);
//            }
//            //目的是为了删除jar包添加的水印
//            buffer = buffer.replaceAll("Evaluation Warning : The document was created with Spire.PDF for Java.","");
//            buffer = buffer.replaceAll("Evaluation Warning : The document was created with Spire.PDF for Java.","");
//
//        } catch (Exception e) {
////            e.printStackTrace();
//        }
//        return stringJson(buffer);
//    }

    /**
     * 读取pdf内容
     * @param path
     * @return
     */
//    public static String readPdfText(String path) {
//        String text = "";
//        try {
//            byte[] bytes = getBytes(path);
//            //加载PDF文档
//            PDDocument document = PDDocument.load(bytes);
//            PDFTextStripper stripper = new PDFTextStripper();
//            text = stripper.getText(document);
//        } catch (IOException e){
//            e.printStackTrace();
//        }
//        return text;
//    }




    /**
     * 根据不同类型，获取内容
     *
     * @param path
     * @return
     */
    public static String readContent(String path,String suffix) {
        String str = "";
        switch (suffix) {
            case "doc":
            case "docx":
                str = readWord(path,suffix);
                break;
            case "xls":
            case "xlsx":
                str = readExcel(path,suffix);
                break;
//            case "pdf":
//                str = readPdf(path);
//                break;
            default:
                break;
        }
        return str;
    }


    /**
     * 将文件转换为byte数组
     * @param filePath
     * @return
     */
    private static byte[] getBytes(String filePath){
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }


}